package com.springboot.middleware.middleware_redisson.server.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.middleware.middleware_redisson.model.entity.SysLog;
import com.springboot.middleware.middleware_redisson.model.mapper.SysLogMapper;
import com.springboot.middleware.middleware_redisson.server.dto.UserLoginDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@EnableAsync
public class SysLogServiceImpl implements SysLogService {
    private static final Logger log = LoggerFactory.getLogger(SysLogServiceImpl.class);
    @Autowired
    private SysLogMapper sysLogMapper;
    //定义JSON序列化和反序列化组件
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 将用户登陆成功的信息记入数据库
     *
     * @param dto UserLoginDto
     */
    @Async
    @Override
    public void recordLog(UserLoginDto dto) {
       try {
           SysLog sysLog = new SysLog();
           sysLog.setUserId(dto.getUserId());
           sysLog.setModule("用户登陆模块");
           sysLog.setData(objectMapper.writeValueAsString(dto));
           sysLog.setCreateTime(new Date());

           //插入数据库
           sysLogMapper.insertSelective(sysLog);
       } catch (Exception e) {
           log.error("系统日志服务-记录用户登陆成功的信息入数据库-发生异常: {} ", dto, e.fillInStackTrace());
       }
    }
}
